import Service from './service';
import { RequestConfig } from './type/index';
import { createDiscreteApi } from 'naive-ui';
import { AxiosResponse } from 'axios';
const { message } = createDiscreteApi(['message']);
//先初始化请求实例
//根据返回的状态码来进行提示
const showStatus = (status: number) => {
  let message = '';
  switch (status) {
    case 400:
      message = '请求错误(400)';
      break;
    case 401:
      message = '未授权，请重新登录(401)';
      break;
    case 403:
      message = '拒绝访问(403)';
      break;
    case 404:
      message = '请求出错(404)';
      break;
    case 408:
      message = '请求超时(408)';
      break;
    case 500:
      message = '服务器错误(500)';
      break;
    case 501:
      message = '服务未实现(501)';
      break;
    case 502:
      message = '网络错误(502)';
      break;
    case 503:
      message = '服务不可用(503)';
      break;
    case 504:
      message = '网络超时(504)';
      break;
    case 505:
      message = 'HTTP版本不受支持(505)';
      break;
    default:
      message = `连接出错(${status})!`;
  }
  return `${message}，请检查网络或联系管理员！`;
};
const request = new Service({
  //这里的配置就是axios的基本配置。可以根据不同的项目进行不同的配置
  baseURL: '',
  timeout: 1000 * 60 * 5,
  interceptors: {
    // 请求拦截器
    requestInterceptors: (config) => {
      console.log('实例请求拦截器');
      return config;
    },
    requestInterceptorsCatch: (err) => {
      console.log(err, '实例请求拦截器错误');
      return Promise.reject(err);
    },
    // 响应拦截器
    responseInterceptors: (result: AxiosResponse) => {
      console.log('实例响应拦截器', result.data);
      if (result.data.code !== 200) {
        message.error('数据请求有问题！');
      }
      return result;
    },
    responseInterceptorsCatch: (err) => {
      const status = err.response?.status;
      const errMessage = showStatus(status as number);
      console.log(errMessage, '实例响应拦截器错误');
      message.error(errMessage);
      return Promise.reject(err);
    },
  },
});

//然后进行请求封装。
export const http = (config: RequestConfig) => {
  //不管是get还是post。都可以使用‘data’字段传参进来
  const method = config.method || 'get'; //默认get
  if (method == 'get' || method == 'GET') {
    if (config?.params && config?.data) {
      config.params = Object.assign(config.params, config.data);
    }
  }
  return request.request({
    ...config,
  });
};

//常用的方法(这里的传参就和直接使用axios实例是一样的了)
export const httpGet = (config: RequestConfig) => {
  return request.request({
    ...config,
    method: 'get',
  });
};
export const httpPost = (config: RequestConfig) => {
  return request.request({
    ...config,
    method: 'post',
  });
};
export const httpDelete = (config: RequestConfig) => {
  return request.request({
    ...config,
    method: 'delete',
  });
};
export const httpPut = (config: RequestConfig) => {
  return request.request({
    ...config,
    method: 'put',
  });
};
